﻿using HZY.Quartz;
using HZY.Quartz.Common;
using HZY.Quartz.Common.Redis;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;

namespace HZY.Quartz.Service.Impl
{
    /// <summary>
    /// 数据服务
    /// </summary>
    public class DataService : IDataService
    {
        private readonly string _webRootPath;
        private string PathOrKey { get; set; }
        private readonly IDataStorageConfigurationService _dataStorageConfigurationService;
        private readonly IRedisService _redisService;

        public DataService(IWebHostEnvironment webHostEnvironment, IDataStorageConfigurationService dataStorageConfigurationService, IRedisService redisService)
        {
            _webRootPath = webHostEnvironment.WebRootPath;
            _dataStorageConfigurationService = dataStorageConfigurationService;
            _redisService = redisService;
        }

        public bool Init(string pathOrKey)
        {
            PathOrKey = pathOrKey;
            return true;
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public async Task<IEnumerable<T>> ReadDataAsync<T>()
        {
            var data = string.Empty;

            if (_dataStorageConfigurationService.IsUseRedis())
            {
                data = await this._redisService.Database.StringGetAsync(PathOrKey);
            }
            else
            {
                try
                {
                    var path = this.GetPath();

                    //using var fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    //var buffer = new byte[fs.Length];
                    //fs.Position = 0;
                    //await fs.ReadAsync(buffer, 0, buffer.Length);

                    //var data = Encoding.UTF8.GetString(buffer);

                    //if (string.IsNullOrWhiteSpace(data)) return default;

                    data = await File.ReadAllTextAsync(path);
                }
                catch (Exception)
                {
                    return await ReadDataAsync<T>();
                }
            }

            return string.IsNullOrWhiteSpace(data) ? default : JsonConvert.DeserializeObject<IEnumerable<T>>(data);
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <returns></returns>
        public async Task<bool> WriteDataAsync<T>(T contents)
        {
            var json = JsonConvert.SerializeObject(contents);

            if (_dataStorageConfigurationService.IsUseRedis())
            {
                await this._redisService.Database.StringSetAsync(PathOrKey, json);
            }
            else
            {
                try
                {
                    var path = this.GetPath();

                    //using var fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                    //fs.Seek(0, SeekOrigin.Begin);
                    //fs.SetLength(0);

                    //var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(contents));

                    //fs.Position = 0;
                    //await fs.WriteAsync(data, 0, data.Length);

                    await File.WriteAllTextAsync(path, json);

                }
                catch (Exception)
                {
                    return await WriteDataAsync(contents);
                }
            }

            return true;
        }


        #region 私有

        private string GetPath()
        {
            if (string.IsNullOrWhiteSpace(PathOrKey)) throw new MessageBox("属性 FilePath 空对象,请使用前调用 Init 函数!");

            var path = _webRootPath + PathOrKey;

            if (!File.Exists(path))
            {
                File.Create(path);
            }

            return path;
        }

        #endregion


    }
}
